/* Kabayan Kamus Light Eition
 * Copyright (C) 2011 A. Sofyan Wahyudin
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 */

import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.wireless.messaging.MessageConnection;
import javax.wireless.messaging.TextMessage;

public class Kabayan extends MIDlet implements CommandListener {
    private Display display;
    
    private Command cmdKeluar      = new Command("Keluar", Command.EXIT, 2); 
    private Command cmdCari        = new Command("Cari", Command.OK, 1);
    private Command cmdToMenu      = new Command("Kembali", Command.BACK, 2);
    private Command cmdToEntryKata = new Command("Kembali", Command.BACK, 2); 
    private Command cmdToListKata  = new Command("Kembali", Command.BACK, 2); 
    private Command cmdSendSMS     = new Command("Kirim SMS", Command.BACK, 3); 
    private Command cmdSend        = new Command("Kirim", Command.BACK, 3); 
    
    private String[] menu = {"Translate", "Sunda-Indonésia", "Indonésia-Sunda", "Help", "About"};
    private String[] ret = {""};
    private String[][] hasil;
    
    private Image[] icon = {null, null, null, null, null};
    
    private TextBox tbNomor = new TextBox("Masukan Nomor", "", 25, 0); 
    private TextBox tbCari = new TextBox("Cari Kata", "", 25, 0);
    private List lsUtama   = new List("KabayanLE", List.IMPLICIT, menu, null);
    private List lsKata    = new List("Result", List.IMPLICIT, ret, null);;
    
    private Paluruh paluruh = new Paluruh();

    protected void destroyApp(boolean unconditional) throws MIDletStateChangeException {
    }

    protected void pauseApp() {
    }

    protected void startApp() throws MIDletStateChangeException {
        
        initKabayan();
    }
    
    public void commandAction(Command c, Displayable d) {
        
        if (c.getCommandType() == Command.SCREEN){
            String judul = display.getCurrent().getTitle();
            
            if (judul.equals(lsUtama.getTitle())) 
                menuUtama(lsUtama.getSelectedIndex());
            else if (judul.equals(lsKata.getTitle())) 
                tampilkanArti(hasil[lsKata.getSelectedIndex()]);
        }
        
        
        if (c == cmdCari) tampilkanKata(tbCari.getString());
        else if (c == cmdToMenu) display.setCurrent(lsUtama);
        else if (c == cmdToListKata) display.setCurrent(lsKata);
        else if (c == cmdToEntryKata) display.setCurrent(tbCari);
        else if (c == cmdSendSMS) display.setCurrent(tbNomor);
        else if (c == cmdSend) {
            sendSMS(tbNomor.getString(), "pesan ti Kabayan");
            display.setCurrent(lsUtama);
        }        
        else if (c == cmdKeluar) notifyDestroyed();
    }
    
    private void initKabayan(){
        display = Display.getDisplay(this);
        
        try{
            icon[0] = Image.createImage("/img/translate.png");
            icon[1] = Image.createImage("/img/find.png");
            icon[2] = Image.createImage("/img/find.png");
            icon[3] = Image.createImage("/img/help.png");
            icon[4] = Image.createImage("/img/about.png");

            lsUtama   = new List("KabayanLE", List.IMPLICIT, menu, icon);
        } catch(Exception ex) { }
        
        lsUtama.addCommand(cmdKeluar);
        lsUtama.setCommandListener(this);
        
        tbCari.addCommand(cmdCari);
        tbCari.addCommand(cmdToMenu);
        tbCari.setCommandListener(this);
        
        tbNomor.addCommand(cmdSend);
        tbNomor.setCommandListener(this);
        display.setCurrent(lsUtama);
        
    }
    
    private void menuUtama(int i){
        switch (i){
            case 0:
                Alert al = new Alert("Sorry ...", "belum tersedia!", null, AlertType.CONFIRMATION);
                display.setCurrent(al);
                break;
            case 1:
                entryKata("001");
                break;
            case 2:
                entryKata("002");
                break;
            case 3:
                showForm("Help", "Tulis teks lalu tekan tombol Cari, maka hasil pencarian akan tampil\n\nUntuk beberapa jenis HP gunakan OK/Call untuk memilih list", cmdToMenu, null);
                break;
            case 4:
                showForm("About Kabayan", "Light Edition v0.1\n© 2011 Sofyan\n\nUrl:\nhttp://code.google.com/p/kabayan/\n\nImage by Fugue Icons", cmdToMenu, null);
                break;
        }
    }
    
    private void showForm(String j, String s, Command c1, Command c2){
        Form f = new Form(j);
        
        f.append(new StringItem("", s));
        f.addCommand(c1);
        if (c2!=null) f.addCommand(c2);
        f.setCommandListener(this);
        
        display.setCurrent(f);
    }
    
    private void entryKata(String idxfile){
        try{
            paluruh.setIndexFile(idxfile);
        } catch (Exception ex) {};
        
        display.setCurrent(tbCari);
    }
    
    private void tampilkanKata(String s){
        
        if (s.indexOf(" ")!=-1) s=splitString(s, " ")[0];
        
        hasil = paluruh.startSearch(s.toLowerCase());
        
        if (hasil==null || hasil.length<1) {
            while (s.length()>1){
              
                s = s.substring(0, s.length()-1);
                hasil = paluruh.startSearch(s.toLowerCase());
              
                if (hasil!=null && hasil.length>0) break;
            }
        }
        
        if (hasil!=null && hasil.length>0) {
        
            ret = new String[hasil.length];
            //System.arraycopy(hasil[], 0, ret, 0, ret.length); 
            //for ()
            
            for (int i=0; i<ret.length; i++)
                ret[i] = realKata(hasil[i][0]);
            
            lsKata = new List("Result", List.IMPLICIT, ret, null);

            lsKata.addCommand(cmdToEntryKata);
            lsKata.setCommandListener(this);

            display.setCurrent(lsKata);
        } else {
            Alert alResult = new Alert("Result", "Tidak ada!", null, AlertType.CONFIRMATION);
            
            alResult.addCommand(cmdToEntryKata);
            alResult.setTimeout(5000);
            
            display.setCurrent(alResult);
        }
    }
    
    private static String realKata(String s){
        if (s.indexOf("|") != -1) 
            return s.substring(s.indexOf("|")+1);
        else
            return s;
    }
    
    //private void tampilkanArti(String s){
    private void tampilkanArti(String[] word){
        try{
            showForm(realKata(word[0]), paluruh.getLine("y"+word[1], word[2]), cmdToListKata, null);
        } catch (Exception ex) {ex.printStackTrace();}
        
    }
    
    private static String[] splitString(String s, String pemisah) {
        Vector nodes = new Vector();
        
        // Parse node ke vektor
        int idx = s.indexOf(pemisah);
        int l = pemisah.length();
        
        while(idx>=0)
        {
            nodes.addElement(s.substring(0, idx));
            s = s.substring(idx+l);
            idx = s.indexOf(pemisah);
        }
        
        // sesa node terakhir
        nodes.addElement(s);

        // Buat split string array
        int size = nodes.size();
        String[] ret = new String[size];
        if (size>0) {
            for(int i=0; i<size; i++)
                ret[i] = (String)nodes.elementAt(i);
        }
        
        nodes = null;
        
        return ret;
    }
    
    private void sendSMS(String nomor, String pesan){
        String notel = "sms://" + nomor + ":1099";
        try{
            MessageConnection mc = (MessageConnection)Connector.open(notel);
            TextMessage tm = (TextMessage)mc.newMessage(MessageConnection.TEXT_MESSAGE);
            tm.setPayloadText(pesan);
            mc.send(tm);
            mc.close();
        } catch (Exception ex) {ex.printStackTrace();}
    }
    
   
    
    
    
}
